# -*- coding: utf-8 -*-
import datetime

from django.db.models import Q
from rest_framework import serializers

from app.device.models import DeviceCtrlLog
from dvadmin.system.models import Structures, RoadsInfos
from dvadmin.utils.json_response import SuccessResponse, DetailResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class DeviceCtrlLogSerializer(CustomModelSerializer):
    """
    设备控制日志-序列化器
    """
    device_code = serializers.CharField(source='deviceid.devicecode', read_only=True)

    class Meta:
        model = DeviceCtrlLog
        # fields = ['id', 'device_id', 'ctrltime', 'info', 'userid', 'username', 'structid', 'devicetype', 'device_code']
        fields = '__all__'
        read_only_fields = ["id"]


class DeviceCtrlLogViewSet(CustomModelViewSet):
    """
    设备控制日志
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = DeviceCtrlLog.objects.order_by('-ctrltime')
    serializer_class = DeviceCtrlLogSerializer

    # filter_fields = ['device_id', 'ctrltime', 'userid', 'username', 'structid', 'devicetype']

    def get_ctrl_log_by_condition(self, request, *args, **kwargs):
        '''
            根据传入参数，获取区域预案细分预案信息
            deviceid    :设备id
            userid      :操作用户id
            structid    :构造物id
            devicetype  :设备类别id
            ctrltime    :操作时间 时间格式 2023-04-24,2023-04-29
        '''
        params = request.query_params
        deviceid = params.get('deviceid', None)
        userid = params.get('userid', None)
        structid = params.get('structid', None)
        devicetype = params.get('devicetype', None)
        ctrltime = params.get('ctrltime', None)
        instance = DeviceCtrlLog.objects.all()
        if deviceid:
            instance = instance.filter(deviceid__id=deviceid)
        if userid:
            instance = instance.filter(userid=userid)
        if structid:
            instance = instance.filter(structid=structid)
        if devicetype:
            instance = instance.filter(devicetype=devicetype)
        if ctrltime:
            '''
                传入时间参数判定
                1、如果有开始时间以及结束时间（2023-04-24,2023-04-29）,拆分之后作为时间段
                2、如果只有一个时间，则选择当天时间
            '''
            start, end = str(ctrltime).split(',') if ',' in ctrltime else (ctrltime, None)
            if end is None:
                end = start
            start = datetime.datetime.strptime(start, "%Y-%m-%d")
            end = datetime.datetime.strptime(end, "%Y-%m-%d") + datetime.timedelta(days=1)
            instance = instance.filter(ctrltime__gte=start, ctrltime__lte=end)
        page = self.paginate_queryset(instance)
        if page is not None:
            serializer = DeviceCtrlLogSerializer(page, many=True, request=request)
            return self.get_paginated_response(serializer.data)
        serializer = DeviceCtrlLogSerializer(instance, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")
